#!/bin/bash 

#time sudo ./quickinstall 2>&1 | tee ./log.txt

export COLOR=y
PROFILE_DIR="profiles"
SP_CUSTOM_DIR="${PROFILE_DIR}/sp_custom"
DRY_RUN="n"
TARGET=/dev/sda8
DESTDIR=""
LOG=""
ERR_LOG=""
PACKLIST=""
QUICK_INSTALL="y"
LISTDIR=""
PACMAN=pacman
#CUSTOM_REPO=/mnt/sda3/cpkg
CACHE=""
MOUNT_AUFS="n"
MOUNT_TARGET="n"
DOWNLOAD="n"
PACKAGE_DIR=""
time=5




RST="\033[1;0m"
# regular colors
K="\033[0;30m"    # black
R="\033[0;31m"    # red
G="\033[0;32m"    # green
Y="\033[0;33m"    # yellow
B="\033[0;34m"    # blue
M="\033[0;35m"    # magenta
C="\033[0;36m"    # cyan
W="\033[0;37m"    # white
# emphasized (bolded) colors
EMK="\033[1;30m"
EMR="\033[1;31m"
EMG="\033[1;32m"
EMY="\033[1;33m"
EMB="\033[1;34m"
EMM="\033[1;35m"
EMC="\033[1;36m"
EMW="\033[1;37m"
# background colors
BGK="\033[40m"
BGR="\033[41m"
BGG="\033[42m"
BGY="\033[43m"
BGB="\033[44m"
BGM="\033[45m"
BGC="\033[46m"
BGW="\033[47m"

HYB="\033[1;33;44m"
HGK="\033[1;32;40m"
HBK="\033[1;34;40m"
HWK="\033[1;37;40m"
HRK="\033[1;31;40m"

plain() { 
	if [ $# -eq 2 ] && [ "$1" = "-n" ]; then
		if [ "${COLOR}" = "y" ]; then 
			echo -n -e "$W$RST      $2$RST"
		else
			echo -n -e "      $2"
		fi
	else
		if [ "${COLOR}" = "y" ]; then 
			echo -e "$W$RST      $@$RST"
		else
			echo -e "      $@"
		fi
	fi
}
msg() {
	if [ "${COLOR}" = "y" ]; then 
		echo -e "$EMB==>$RST$HWK $@$RST"
	else
		echo -e "==> $@"
	fi
}
msg2() {
	if [ $# -eq 2 ] && [ "$1" = "-n" ]; then
		if [ "${COLOR}" = "y" ]; then 
			echo -n -e "$HBK   ->$RST$W $2$RST"
		else
			echo -n -e "  -> $2"
		fi
	else
		if [ "${COLOR}" = "y" ]; then 
			echo -e "$HBK   ->$RST$W $@$RST"
		else
			echo -e "  -> $@"
		fi
	fi
}
warn() {
	if [ "${COLOR}" = "y" ]; then 
		echo -e "\n$Y==> $(gettext "WARNING:") $@$RST"
	else
		echo -e "\n ==> $(gettext "WARNING:") $@"
	fi
}
error() {
	if [ "${COLOR}" = "y" ]; then 
		echo -e  "\n$HRK==> $(gettext "ERROR:") $@$RST"
	else
		echo -e "\n==> $(gettext "ERROR:") $@"
	fi
}
hgreen() {
	if [ "${COLOR}" = "y" ]; then
		echo -e "$HGK      $@$RST"
	else
		echo "      $@"
	fi
}
green() {
	if [ "${COLOR}" = "y" ]; then
		echo -e "$G      $@$RST"
	else
		echo -e "      $@"
	fi
}
yellow() {
	if [ "${COLOR}" = "y" ]; then
		echo -e "$HYB$@$RST"
	else
		echo -e "$@"
	fi
}

info () {
	if [ "${COLOR}" = "y" ]; then
		echo -e "$G      $@$RST"
	else
		echo -e "      $@"
	fi

}

usage ()
{
    echo "usage 程序名 [选项] 命令 <命令选项>"
    echo " 一般选项:"
    #echo "    -f               强制覆盖现有的工作目录等，全部重新制作"
    echo "    -t TARGET        预安装的目标分区."
    echo "    -c CACHE DIR     Arch软件包存储位置"
    echo "    -C CUSTOM_REPO	  本地自定义repo"
    echo "    -d DESTDIR         工作文件临时挂载位置"
    echo "    -l LOG_FILE       保存正常输出的log文件"
    echo "    -e ERR_LOG_FILE     保存出错信息的log文件"
    echo "    -p PACKLIST       包列表保存目录"
    echo "    -m MOUNT_DIR     仅挂载指定目录的proc dev sys"
    echo "    -u UMOUNT_DIR     仅卸载指定目录的proc dev sys"
    echo "    -w                仅下载但不安装"
    echo "    -n                仅测试不真正运行安装"
    echo "    -h               本帮助信息."
    exit $1
}

#error () { echo -e "\033[1;31;40m!!! \033[1;37;40m$@\033[1;0m"; }
#warn ()  { echo -e "\033[1;33;40m*** \033[1;37;40m$@\033[1;0m"; }
#info () { echo -e "\033[1;32;40m>>> \033[1;37;40m$@\033[1;0m"; }


function get_pkgname () {
   # $1  软件包清单
   # 该函数将软件包清单中需要检测依赖关系的软件包以空格相隔返回到变量PKGNAME
   pkgname=$(awk 'BEGIN {dep_pkg=""}{if ($1 !~ /^#+/) {if (NF == 1) {dep_pkg=dep_pkg " " $1}}}END {print dep_pkg}' $1)
}
function get_d_pkgname () {
   # $1  软件包清单
   # 该函数将软件包清单中无需检测依赖关系的软件包以空格相隔返回到变量PKGNAME
   pkgname=$(awk 'BEGIN {nodep_pkg=""}{if ($1 !~ /^#+/) { if (NF == 2) {nodep_pkg=nodep_pkg " " $2}}}END {print nodep_pkg}' $1)
}
function get_all_pkgname () {
   # $1  软件包清单
   # 该函数将软件包清单中所有软件包以空格相隔返回到变量PKGNAME
   pkgname=$(awk 'BEGIN {all_pkg=""}{if ($1 !~ /^#+/) { {all_pkg=nodep_pkg " " $1" "$2}}}END {print all_pkg}' $1)
}

function pac_install () {
    if [ "${DRY_RUN}" = "y" ] ; then
        echo "pkgname = $pkgname"
        return 0
    fi
    if [ "$DOWNLOAD" = "n" ] ; then
        $PACMAN -S -f --needed --noconfirm --config "${PACMANCONF}" --cachedir "$CACHE" -r "${DESTDIR}" $pkgname | tee -a ${LOG} 
    else
        $PACMAN -S -w --needed --noconfirm --config "${PACMANCONF}" --cachedir "$CACHE" -r "${DESTDIR}" $pkgname | tee -a ${LOG} 
    fi
    #echo "pkgname = $pkgname"
	case $? in
	   #0) (green "软件包${pkgname/-d /} 安装成功! " | tee -a ${LOG} ) ; break;;
	   0) (green "软件包${pkgname/-d /} 安装成功! " | tee -a ${LOG} ) ;;
       1) 
        if [ -e ${PACKLIST}/available.list ] ; then
            pkgname=${pkgname/-d /}
            for pkg in $pkgname; do
                if [ "x$(grep $pkgname ${PACKLIST}/available.list)" != "x" ]; then
                    error "安装$pkgname出错" | tee -a ${LOG}
                    #cat $log >> ${BUILDLOG}/${mod}-errors.log
                    error "安装$pkgname出错" | tee -a ${ERR_LOG}
                    #break
                else
                    error "现有软件仓中无 $pkgname, 忽略" | tee -a ${LOG}
                    error "现有软件仓中无 $pkgname, 忽略" | tee -a ${ERR_LOG}
                    #break
                fi
            done
        fi
        ;;
	    #255) exit;;
    esac
    #echo "pac_install over!!!" 
}

function check_continue()
{
    if [ "${DRY_RUN}" = "y" ] ; then
        info "${FUNCNAME} 检测到是模拟运行,返回"
        return 1
    fi
    if [ "$DOWNLOAD" = "y" ] ; then
        info "${FUNCNAME} 检测到是下载模式,返回"
        return 1
    fi
    return 0
}


# $1 预创建repo的文件夹——软件包存放位置
# $2 预创建的repo仓库名称
create_repo ()
{
	for pkgfile in $(ls $1/*.pkg.tar.gz); do
		repo-add $1/$2.db.tar.gz $pkgfile
	done
}

function do_mount_info()  {
   if [ -d ${DESTDIR}/proc ] ; then
       if [ -d ${DESTDIR}/sys ] ; then
           mount -t proc proc ${DESTDIR}/proc
           mount -t sysfs sysfs ${DESTDIR}/sys
           mount -o bind /dev ${DESTDIR}/dev
           mount -t devpts devpts ${DESTDIR}/dev/pts/
       fi
   fi
}


function do_umount_info()  {
   umount  ${DESTDIR}/dev/pts/
   umount  ${DESTDIR}/dev
   umount  ${DESTDIR}/sys
   umount  ${DESTDIR}/proc
}

function check_param()
{
    if [ "$EUID" != "0" ]; then
        echo "错误: 必须以root用户运行本制作脚本."
        exit 1
    fi

    if [ "${arch}" != "i686" ] && [ "${arch}" != "x86_64" ] ; then
        error "arch != i686 and arch != x86_64"
        exit 1
    fi
    if [ "x${DESTDIR}" = "x" ] ; then
        DESTDIR="$(pwd)/install_dir_${arch}"
    fi
    if [ "x${CACHE}" = "x" ] ; then
        CACHE="${DESTDIR}/var/cache/pacman/pkg"
    elif [ ! -d ${CACHE} ] ; then
        CACHE="${DESTDIR}/var/cache/pacman/pkg"
    fi
    if [ "x${LISTDIR}" = "x" ] ; then
        LISTDIR="list-${arch}"
    fi
    if [ "x${PACKLIST}" = "x" ] ; then
        PACKLIST="$(pwd)/packlist"
    fi
    if [ "x${LOG}" = "x" ] ; then
        LOG="$(pwd)/install_log.txt"
    fi
    if [ "x${ERR_LOG}" = "x" ] ; then
        ERR_LOG="$(pwd)/install_error_log.txt"
    fi
    if [ "x${OVERLAY}" = "x" ] ; then
        USE_OVERLAY="n"
    elif [ ! -d ${OVERLAY} ] ; then
        USE_OVERLAY="n"
    fi
    # 装载软件仓等相关配置
    PACMANCONF="$(pwd)/${PROFILE_DIR}/pacman_${arch}.conf"
    if [ ! -f "${PACMANCONF}" ]; then
        error "count load pacman.conf"
        exit 1
    fi
	# 更新安装时候的软件缓存位置
#	[ -f $PACMANCONF ] && sed -i "s%.*CacheDir.*%CacheDir = $CACHE%g" $PACMANCONF
    if [ "x${PACKAGE_DIR}" = "x" ] ; then
        PACKAGE_DIR=$(pwd)/${arch}-packages
    fi
    if [ "x${PKGFILE}" = "x" ] ; then
        PKGFILE="${PACKAGE_DIR}/${arch}-packages.list"
    fi
    if [ "x${UMOUNT_DIR}" != "x" ] ; then
        DESTDIR=${UMOUNT_DIR}
        info "start umount ${DESTDIR}"
        do_umount_info
        info "umount ${DESTDIR} over"
        exit 0
    fi
    if [ "x${MOUNT_DIR}" != "x" ] ; then
        DESTDIR=${MOUNT_DIR}
        info "start mount ${DESTDIR}"
        do_mount_info 
        info "mount ${DESTDIR} over"
        exit 0
    fi
}

function grub_install_tips()
{
    #>/tmp/grub.log 2>&1"
    ROOTDEV="/dev/sdX"
    info "=============================================="
    info "run $DESTDIR/sbin/grub-install --recheck --grub-shell=$DESTDIR/sbin/grub --root-directory=$DESTDIR $ROOTDEV"
    info "vim $DESTDIR/etc/mkinitcpio.conf" 
    info "run pacman -S kernel26"
    info "run locale-gen"
    info "vim $DESTDIR//etc/mkinitcpio.d/kernel26.kver"
    info "/sbin/mkinitcpio -p kernel26"
    info "-k KERNELVERSION Use KERNELVERSION. default: 2.6.35-ARCH"
    info "-b BASEDIR       Use BASEDIR. default: /"
    info "创建启动镜像"
    info "${DESTDIR}/sbin/mkinitcpio -b ${DESTDIR} -c ${DESTDIR}/etc/mkinitcpio.conf -g ${DESTDIR}/boot/kernel26.img"
    info "${DESTDIR}/sbin/mkinitcpio -b ${DESTDIR} -c ${DESTDIR}/etc/mkinitcpio.conf -g ${DESTDIR}/boot/kernel26-fallback.img -S autodetect"
    info "vim $DESTDIR/boot/grub/menu.lst"
    info "=============================================="
}


function show_param()
{
    info "=============================="
    info "arch=${arch}"
    info "DESTDIR=${DESTDIR}"
    info "CACHE=${CACHE}"
    info "LISTDIR=${LISTDIR}"
    info "PACMANCONF=${PACMANCONF}"
    info "DOWNLOAD=${DOWNLOAD}"
    info "DRY_RUN=${DRY_RUN}"
    info "PKGFILE=${PKGFILE}"
    info "SP_CUSTOM_DIR=${SP_CUSTOM_DIR}"
    info "=============================="
    echo ""
    grub_install_tips
    echo ""
    echo " 需要制作的模块为: $(echo ${MODULES} | tr -s "\n" " ")"
    info "you can run as 'time sudo ./quickinstall 2>&1 | tee ./log.txt'"
    hgreen "***如果以上不是你想要的，Ctrl+C 终止程序的执行，并检测相关配置文件.***"
    echo -n "                            "; yellow "5 秒后开始程序"
    echo "-----------------------------------------------------------------------------"
    sleep $time
    echo ""
}

unset MODULES

if [ -f $(pwd)/${PROFILE_DIR}/qi.conf ] ; then
    source $(pwd)/${PROFILE_DIR}/qi.conf
else
    error "count load $(pwd)/${PROFILE_DIR}/qi.conf"
    exit 1
fi

#实际需要的模块 (去掉#)
MODULES=$(echo $MODULES | tr -s " " "\n" | grep -v "#")
EXTRAMODULES=$(echo $EXTRAMODULES | tr -s " " "\n" | grep -v "#")

# 检测、配置输入的命令
while getopts 'c:C:d:e:l:m:np:t:u:wnvSh' arg; do
    case "${arg}" in
	c) CACHE="${OPTARG}" ;;
	C) CUSTOM_REPO="${OPTARG}" ;;
	d) DESTDIR="${OPTARG}" ;;
    e) ERR_LOG="${OPTARG}" ;;
    l) LOG="${OPTARG}" ;;
	m) MOUNT_DIR="${OPTARG}" ;;
    n) DRY_RUN="y";;
    p) PACKLIST="${OPTARG}" ;;
	t) TARGET="${OPTARG}" ;;
	u) UMOUNT_DIR="${OPTARG}" ;;
	v) QUIET="n" ;;
    w) DOWNLOAD="y";;
    S) SP_CUSTOM_DIR="";;
    h|?) usage 0 ;;
    *) echo "无效参数 '${arg}'"; usage 1 ;;
    esac
done
APPNAME=$(basename "${0}")
check_param
show_param

info "准备文件系统"
if [ "$DOWNLOAD" = "y" ] ; then
    info "仅是下载文件,不进行安装"
fi


info "开始安装程序"

old_list=""
new_list="" 
install_list=""
no_pkg_list=""

echo "MODULES=$MODULES"

function cmd_install ()  {
    local old_list new_list install_list no_pkg_list
    for mod in ${MODULES}; do
        echo "mod = $mod"
        old_list="${PROFILE_DIR}/$LISTDIR/${mod}.list"
        new_list="${PACKLIST}/${mod}.new"
        install_list="${PACKLIST}/${mod}.install"
        no_pkg_list="${PACKLIST}/${mod}.no_pkg"

        [ "x$(tail -1 ${old_list})" = "x" ] || (echo >>"${old_list}")
        cat "${old_list}" | sed -r "s/#.*//g" | sed -r "/^$/d" > ${new_list}
        green "完成!" | tee -a ${LOG}

        rm -f $install_list > /dev/null
        rm -f $no_pkg_list > /dev/null
        cat ${new_list} | while read pkgname; do
        pkgname=${pkgname#-d }
        if grep " $pkgname " ${PACKLIST}/available.list >/dev/null; then
            echo "$pkgname" >> $install_list
            continue
        elif grep "$pkgname " ${PACKLIST}/group_detail.list >/dev/null; then
            echo "$pkgname" >> $install_list
            continue
        else
            echo "$pkgname" >> $no_pkg_list
            warn "模块 ${mod} 中指定的软件 $pkgname 无法从当前设定的软件仓中找到。" | tee -a ${LOG}
            warn "模块 ${mod} 中指定的软件 $pkgname 无法从当前设定的软件仓中找到。" | tee -a ${ERR_LOG}
        fi
    done
    rm -f  ${PACKLIST}/${mod}.order > /dev/null
    if [ "${QUICK_INSTALL}" = "y" ] ; then
        get_pkgname $install_list 
        #${PROFILE_DIR}/$LISTDIR/${mod}.list
        if [ "x${pkgname}" != "x" ] ; then
            echo "$pkgname" >> ${PACKLIST}/${mod}.order
            pac_install
        fi
    else 
        #cat  "${PACKLIST}/${mod}.new" | while read pkgname; do
        cat  "${install_list}" | while read pkgname; do
            [ "x$pkgname" = "x" ] && continue
            echo "$pkgname" >> ${PACKLIST}/${mod}.order
            pac_install
	    done

    fi

    
    #$PACMAN -Sy --noconfirm --config "${PACMANCONF}" --cachedir "${CACHE}" -fr "${DESTDIR}"
    #cat  "$(pwd)/list" | grep -v "^#" | while read pkgname; do
    #echo "安装 $pkgname"
    #$PACMAN -S -f --needed --noconfirm --config "${PACMANCONF}" --cachedir "$CACHE" -r "${DESTDIR}" $pkgname
    #done
done
}
function custom_install()
{
    check_continue
    if [ $? -ne 0 ] ; then
        warn "${FUNCNAME} 检测到返回"
    fi

   # 导出SP_CUSTOM_DIR特别设置文件（如果有）清单
   if [ "x${SP_CUSTOM_DIR}" != "x" ]; then
	msg2 -n "导出特别设置文件清单..." | tee -a ${LOG}
	find ${SP_CUSTOM_DIR} -type f -name "*" >${PACKLIST}/sp_custom.list
	sed -i "s#${SP_CUSTOM_DIR}/##g" ${PACKLIST}/sp_custom.list
	green "完成！" | tee -a ${LOG}
   fi


	# 特别定制文件	
	if [ "x${SP_CUSTOM_DIR}" != "x" ]; then
		msg2 "拷贝特别设置${SP_CUSTOM_DIR}到目标系统..." | tee -a ${LOG}
		cat ${PACKLIST}/sp_custom.list | while read file; do
			[ -f ${DESTDIR}/$file ] && cp -f ${SP_CUSTOM_DIR}/$file $DESTDIR/$file
		done
		if [ "x$(ls ${DESTDIR}/var/lib/pacman/local | grep "glibc-")" != "x" ]; then
			[ -d ${SP_CUSTOM_DIR}/etc ] && cp -rf ${SP_CUSTOM_DIR}/etc/* $DESTDIR/etc/
			[ -f ${SP_CUSTOM_DIR}/etc/locale.gen ] && chroot $DESTDIR locale-gen
		fi
		[ -f ${DESTDIR}/etc/sudoers ] && chmod 0440 ${DESTDIR}/etc/sudoers
        if [ -f ${SP_CUSTOM_DIR}/etc/mkinitcpio.conf ] ; then
            info "start create ${DESTDIR}/boot/kernel26.img"
            ${DESTDIR}/sbin/mkinitcpio -b ${DESTDIR} -c ${DESTDIR}/etc/mkinitcpio.conf -g ${DESTDIR}/boot/kernel26.img
            info "create kernel26.img over"
            info "start create ${DESTDIR}/boot/kernel26-fallback.img"
            ${DESTDIR}/sbin/mkinitcpio -b ${DESTDIR} -c ${DESTDIR}/etc/mkinitcpio.conf -g ${DESTDIR}/boot/kernel26-fallback.img -S autodetect
            info "create kernel26-fallback.img over"

        fi
		green "完成!" | tee -a ${LOG}
	fi

    [ -e "${DESTDIR}/etc/ld.so.conf" ] && chroot $DESTDIR ldconfig
    #do_locale_file

    $PACMAN -Q -r ${DESTDIR} > ${PKGFILE}
}

function sync_databaes() {
    $PACMAN -Sy --noconfirm --config "${PACMANCONF}" --cachedir "${CACHE}" -fr "${DESTDIR}"
}

function get_available_table()  {
    plain -n "导出可用软件包清单到${PACKLIST}/available.list" | tee -a ${LOG}
    #$PACMAN -Sl >${PACKLIST}/available.list
    $PACMAN -Sl  --config "${PACMANCONF}" --cachedir "$CACHE" -r "${DESTDIR}"  > ${PACKLIST}/available.list
    green "完成!" | tee -a ${LOG}

    plain -n "导出软件仓软件组信息到${PACKLIST}/group_detail.list" | tee -a ${LOG}
    #$PACMAN -Qg >${PACKLIST}/group_detail.list
    $PACMAN -Qg  --config "${PACMANCONF}" --cachedir "$CACHE" -r "${DESTDIR}" >${PACKLIST}/group_detail.list
    green "完成!" | tee -a ${LOG}
}

function do_make_dir() {
    [ ! -d ${DESTDIR} ] && mkdir -p ${DESTDIR}

    if [ "$MOUNT_TARGET" = "y" ] ; then
        mount ${TARGET} ${DESTDIR}
    fi

    if [ "x${CUSTOM_REPO}" != "x" ]; then
        info "建立本地自定义软件仓"
        for db in CUSTOM_REPO/${db}.db.tar.gz; do
            rm -f CUSTOM_REPO/${db}.db.tar.gz
        done
        create_repo ${CUSTOM_REPO} archlive-pkg
    fi

    if [ "$MOUNT_AUFS" = "y" ] ; then
        mount -t aufs -o br:${DESTDIR}=rw aufs ${DESTDIR}
        if [ $? -ne 0 ]; then 
            echo "挂载 $DESTDIR aufs文件系统错误."
            exit 1
        fi
    fi

    if [ "$DOWNLOAD" = "n" ] ; then
        [ ! -d "${DESTDIR}/var/lib/pacman" ] && mkdir -p "${DESTDIR}/var/lib/pacman"	
        [ ! -d "${DESTDIR}/dev" ] && mkdir -p "${DESTDIR}/dev"
        #[ ! -d "${DESTDIR}/proc" ] && mkdir -p "${DESTDIR}/proc"
        #[ ! -d "${DESTDIR}/sys" ] && mkdir -p "${DESTDIR}/sys"

        [ ! -e ${DESTDIR}/dev/console ] && mknod ${DESTDIR}/dev/console c 5 1 >/dev/null
        [ ! -e ${DESTDIR}/dev/null ] && mknod ${DESTDIR}/dev/null c 1 3 >/dev/null
        [ ! -e ${DESTDIR}/dev/zero ] && mknod ${DESTDIR}/dev/zero c 1 5 >/dev/null

        if [ -e "${DESTDIR}/var/lib/pacman/db.lck" ]; then
            rm -f ${DESTDIR}/var/lib/pacman/db.lck
        fi

    fi

    rm -f $LOG > /dev/null
    rm -f $ERR_LOG > /dev/null


    ! [ -d $DESTDIR/var/lib/pacman ] && mkdir -p $DESTDIR/var/lib/pacman
    #! [ -d /var/lib/pacman ] && mkdir -p /var/lib/pacman
    # mount proc/sysfs first, so mkinitrd can use auto-detection if it wants
    ! [ -d $DESTDIR/proc ] && mkdir $DESTDIR/proc
    ! [ -d $DESTDIR/sys ] && mkdir $DESTDIR/sys
    ! [ -d $DESTDIR/dev ] && mkdir $DESTDIR/dev
    if [ "x${PACKAGE_DIR}" != "x" ] ; then
        if [ ! -d ${PACKAGE_DIR} ] ; then
            mkdir -p ${PACKAGE_DIR}
        fi
    fi
    [ ! -d $PACKLIST ] && mkdir -p $PACKLIST
}



function do_locale_file()
{
    check_continue
    if [ $? -ne 0 ] ; then
        warn "${FUNCNAME} 检测到返回"
    fi

    if [ "${USE_OVERLAY}" = "y" ]; then
        locale_gen_file="${OVERLAY}/etc/locale.gen"
    else
        locale_gen_file="${SP_CUSTOM_DIR}/etc/locale.gen"
    fi
    if [ -f "${locale_gen_file}" ]; then
        cp -f ${locale_gen_file} $DESTDIR/etc/
        plain -n "根据定制的locale.gen文件生成locale文件"
        chroot $DESTDIR locale-gen
        green "完成!" | tee -a ${LOG}
    fi
}

function cmd_clean() {
    check_continue
    if [ $? -ne 0 ] ; then
        warn "${FUNCNAME} 检测到返回"
    fi

    info "开始清理文件系统"
    find ${DESTDIR} -type f -name ".wh.*" -exec rm {} \;
    find ${DESTDIR} -type d -name ".wh.*" -exec rm -rf {} \;

    info "删除除zh_CN外的语言文件"
    if [ -d ${DESTDIR}/usr/share/locale ] ; then
        find ${DESTDIR}/usr/share/locale/* -maxdepth 0 -type d ! -iregex ".*zh.CN" -exec rm -rf {} \;
    fi
    if [ -d ${DESTDIR}/usr/share/X11/locale ] ; then
        find ${DESTDIR}/usr/share/X11/locale/* -maxdepth 0 -type d ! -iregex ".*zh.C*" -exec rm -rf {} \;
    fi

    info "删除除zh_CN及英文外的帮助文件"
    if [ -d ${DESTDIR}/usr/share/man ] ; then
        find ${DESTDIR}/usr/share/man/* -maxdepth 0 -type d ! -name "man*" ! -iregex ".*zh.CN" -exec rm -rf {} \;
    fi

    info "将配置文件释放到目标分区"
    if [ -e $(pwd)/overlay.tgz ] ; then
        tar -xzvpf $(pwd)/overlay.tgz -C ${DESTDIR}
    elif [ -d $PROFILE_DIR/overlay ] ; then
        cp -af $PROFILE_DIR/overlay/*  ${DESTDIR}
    fi
    if [ -d $PROFILE_DIR/overlay_custom ] ; then
        cp -af $PROFILE_DIR/overlay_custom/*  ${DESTDIR}
    fi

    if [ "x${OVERLAY}" != "x" ] ; then
        if [ -d $PROFILE_DIR/${OVERLAY} ] ; then
            if [ "${OVERLAY}" != "overlay" ] ; then
                cp -af $PROFILE_DIR/${OVERLAY}/*  ${DESTDIR}
            fi
        fi
    fi
}


do_make_dir
#do_mount_info
sync_databaes
get_available_table
cmd_install 
custom_install

if [ "$MOUNT_TARGET" = "y" ] ; then
    info "卸载并删除临时挂载点${DESTDIR}"
    umount -l ${DESTDIR}
    #rm -rf ${DESTDIR}
fi

cmd_clean

grub_install_tips
#grub-install  --no-floppy  ${DEV}
info "---------------  OVER ----------------"
